package server;

/**
 *@author Adam
 */

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;

public class BonjourListener implements ServiceListener {

	public String host = "";
	public int port = -1;
	public String serviceName = "";
	Server parent;
	public JmDNS jmdns;
	public String SERVICE_TYPE = "";
	
	public BonjourListener(String mySERVICE_TYPE, Server myParent){
		try{
			jmdns = JmDNS.create();
		} catch (Exception e){
			e.printStackTrace();
		}
		jmdns.addServiceListener(mySERVICE_TYPE, this);
		this.parent = myParent;
		this.SERVICE_TYPE = mySERVICE_TYPE;
	}
	
	public void serviceAdded(final ServiceEvent event) {
		System.out.println("Service added   : " + event.getName() + "." + event.getType());
		event.getDNS().requestServiceInfo(event.getType(), event.getName(), 0);
	}
	
	public void serviceRemoved(ServiceEvent event) {

		System.out.println("source = " + event.getSource());
	}
	
	public void serviceResolved(ServiceEvent event) {
		// Display some information about the service.
		host = event.getInfo().getHostAddress();
		port = event.getInfo().getPort();
		serviceName = event.getInfo().getName();
		System.out.println("Service resolved: " + event.getInfo().getName() + ", host: "
				+ event.getInfo().getHostAddress() + ", port: " + event.getInfo().getPort());
		if (port != 1234){
		parent.serviceDiscovered(host,port,serviceName);
		}
//		jmdns.close();
	}
}